package com.question.business.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.question.business.user.entity.UserDept;
import com.question.business.user.mapper.UserDeptMapper;
import com.question.business.user.service.IUserDeptService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 用户部门服务实现类
 *
 * @author star
 * @since 2023-09-15
 */
@Slf4j
@Service
@AllArgsConstructor
public class UserDeptServiceImpl extends ServiceImpl<UserDeptMapper, UserDept> implements IUserDeptService {

    /**
     * 用户部门查询
     *
     * @param userId 用户ID
     * @return List<String> 响应参数
     */
    @Override
    public List<String> queryDeptByUserId(String userId) {
        return baseMapper.queryDeptByUserId(userId);
    }

    /**
     * 部门用户查询
     *
     * @param deptId 部门ID
     * @return List<String> 响应参数
     */
    @Override
    public List<String> queryUserByDeptId(String deptId) {
        return baseMapper.queryUserByDeptId(deptId);
    }

    /**
     * 用户部门新增数据
     *
     * @param userId  用户ID
     * @param deptIds 部门ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUserDept(String userId, List<String> deptIds) {
        // 删除用户部门
        baseMapper.deleteByUserId(userId);
        handleBatchAdd(Collections.singletonList(userId), deptIds);
    }

    /**
     * 处理批量保存
     *
     * @param userIds 用户ID
     * @param deptIds 部门ID
     */
    private void handleBatchAdd(List<String> userIds, List<String> deptIds) {
        if (CollectionUtils.isNotEmpty(userIds) && CollectionUtils.isNotEmpty(deptIds)) {
            List<UserDept> data = new ArrayList<>();
            for (String userId : userIds) {
                for (String deptId : deptIds) {
                    UserDept entity = new UserDept();
                    entity.setUserId(userId);
                    entity.setDeptId(deptId);
                    data.add(entity);
                }
            }
            super.saveBatch(data);
        }
    }

    /**
     * 部门用户新增数据
     *
     * @param deptId  部门ID
     * @param userIds 用户ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addDeptUser(String deptId, List<String> userIds) {
        // 删除部门用户
        baseMapper.deleteByDeptId(deptId);
        handleBatchAdd(userIds, Collections.singletonList(deptId));
    }
}